﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using PicStore.Web.Controllers;

namespace PicStore.Web.Unity
{
    public class UnityControllerFactory : IControllerFactory
    {
        private IUnityContainer _container;
        private IControllerFactory _innerFactory;

        public UnityControllerFactory(IUnityContainer container)
            : this(container, new DefaultControllerFactory())
        {
        }

        protected UnityControllerFactory(IUnityContainer container, IControllerFactory innerFactory)
        {
            _container = container;
            _innerFactory = innerFactory;
        }

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            string name = (controllerName + "Controller").ToLower();
            var controllerTypes = from t in currentAssembly.GetTypes()
                                  where t.Name.ToLower().Contains(name)
                                  select t;

            if (controllerTypes.Count() > 0)
            {
                return _container.Resolve(controllerTypes.First()) as IController;
            }
            return null;
        }

        //public void RegisterControllers()
        //{
        //    Assembly currentAssembly = Assembly.GetExecutingAssembly();
        //    var controllerTypes = from t in currentAssembly.GetTypes()
        //                          where t.Name.ToLower().Contains("controller")
        //                          select t;

        //    if (controllerTypes.Count() > 0)
        //    {
        //        foreach (var type in controllerTypes)
        //        {
        //            _container.Resolve(type);
        //        }
        //    }
        //}

        public void ReleaseController(IController controller)
        {
            _container.Teardown(controller);
        }

        public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
        {
            return System.Web.SessionState.SessionStateBehavior.Default;
        }
    }
}
